package com.wall.haven.util;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {

    //公钥
    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnxjyJ5FbX2Ck2f" +
            "QKgjYVjBPG/BiSq3751X1VwdTa1QsFND7ilBojHo6qfQjGPHa9ywMP1HNhE+9gDKvd5LKaNKEE33b4CqipdrhuTG1Ip" +
            "hNf0Q3Cj8FXgQCAjr4az2IX3Nfb+tMG2OveHhRWTlKunjke7fxTQLGVwnpZaU2tvOJnpUow6RHwWfU6QcoWGd2+sgZt" +
            "eIARNdZONqOYPOPY1qMiZ4tvX3qB+eIjQ6ocbPUtuetNr0Dnq3014KDattKPpnNpOrfMbnRfDjRq2prdsNMM3dlaobR" +
            "RQvdj7APoOPVK69Wzo3O9OygRamQbAPyCBqdr6wmHyWOMEBYWiQ1vxwIDAQAB";
    //私钥
    public static final String PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCfGPInk" +
            "VtfYKTZ9AqCNhWME8b8GJKrfvnVfVXB1NrVCwU0PuKUGiMejqp9CMY8dr3LAw/Uc2ET72AMq93kspo0oQTfdvgKqKl2" +
            "uG5MbUimE1/RDcKPwVeBAICOvhrPYhfc19v60wbY694eFFZOUq6eOR7t/FNAsZXCellpTa284melSjDpEfBZ9TpByhY" +
            "Z3b6yBm14gBE11k42o5g849jWoyJni29feoH54iNDqhxs9S25602vQOerfTXgoNq20o+mc2k6t8xudF8ONGramt2w0w" +
            "zd2VqhtFFC92PsA+g49Urr1bOjc707KBFqZBsA/IIGp2vrCYfJY4wQFhaJDW/HAgMBAAECggEAcXTIu47dKlcxOHzgQ" +
            "ZtwIkS4Um7zqXkTkTugPGoe5G7Hd0qhKhy5jsEOs7veIqBLGMtGLqtZP24lgOPPiZgUgBOT9ghROsiskQ1VGwuUE1sd" +
            "qWe2p+2pCUXiZ+kKFXpOqh8FsQlsiKUr8SdvpMsx24PAmtamSCxcMCQwPvg2PcvU/pLWUhBKbIBw6VUVEP/Kpcxv89g" +
            "+ySP+BbOk7ja/WA66/ACKdgH+OwgtaGTX1gwnfXXtIe+hK2EjS+cf+/O07fEl6lAHBmVubKvKQLairOxbSuI2jnuiK8" +
            "QC6zJ1nbPunZKhePAPZMF4W4rWGyTqk26HbkMVbmcXtdOiPpc6AQKBgQDlpr773XNBuRgd5iC0n7+2jrb9zINt/Nd4J" +
            "clP7IdEHPOgjWP1uXp5xXDuu8cFmm70M65HucQgIiImzZqYVMA/hnUkO/LUsspK87iSAD6B9uXBWpQ9d3E68e8T3N5Z" +
            "TYTMr2y1YjGX139uqcw0vKbKj2cPLfMY0BdbpUQuWdxw8QKBgQCxWekhvMtPjiL5mT2XQWMHfmsZbmr2pkTSgdAlP0u" +
            "XiVFzmHKizc8Ec9v+XYtFebjOoxYj46BYQnD5+A+/QUYEN/lAucNiAbWIer7azNvyAu/3g0icl3N2J86m6nu0hFIwfW" +
            "7e0OTZpBH/Dgz6p5JrsrW980eq6YqOYrHfq8PsNwKBgGF3xuEQ2QUQ8NpnvIPMtUpfAe1v6mw4/p5As1NXmQVgoEoJG" +
            "F7HLOMX2FmKmuqW4/aDJLnObx4QPpxncPCsL7gGchtB0ktR4qezDyfwMJdqWZMZxYbc9dLFsemlOT1/uBhDcAj/tvqx" +
            "/KTULhZH5yZbfKslnmJulytPVkOx4eyRAoGAQKsRSD0IQY0Jkcvf2nx8OKpPMSnDFQcRx1SQalSHIs1uhuEKw/SZzPz" +
            "WNg00EHRPAAIVu6ZvvF8VxQA/9bQ+bKFgYMqbxOvsnsRrPWs/tCKAD9euLXNIJchkIRcVXoB1W7sRJ2wyVm3uJfugnf" +
            "FmgaDbhlTkSBz6aerxAyclvMcCgYAI+gibf6jDeRmFEi7bnrsuh0Pbx0XsXQVXMkT++qeyx8wFGhKYwLvBHiLLWErRk" +
            "039UuFBZdcJAlS7ODO045rc1YybdewX8sE5ag6BZHri/+cl00DilQhXHtIhO2XIP57SyOWgOzVHV5snPnCuZid+Q6/V" +
            "65J4ywBfz7n79oVK/w==";

    /**
     * 获取密钥对
     */
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 公钥加密
     */
    public static String encrypt(String data, String publicKeyString) throws Exception {
        PublicKey publicKey = getPublicKeyFromString(publicKeyString);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 私钥解密
     */
    public static String decrypt(String data, String privateKeyString) throws Exception {
        PrivateKey privateKey = getPrivateKeyFromString(privateKeyString);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = Base64.getDecoder().decode(data);
        return new String(cipher.doFinal(bytes));
    }

    /**
     * 密钥转字符串
     * @param key
     * @return
     */
    public static String keyToString(Key key) {
        byte[] keyBytes = key.getEncoded();
        return Base64.getEncoder().encodeToString(keyBytes);
    }

    /**
     * 将公钥字符串转换为 PublicKey 对象
     */
    private static PublicKey getPublicKeyFromString(String publicKeyString) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    }

    /**
     * 将私钥字符串转换为 PrivateKey 对象
     */
    private static PrivateKey getPrivateKeyFromString(String privateKeyString) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(spec);
    }

}